<template>
  <div>
    <Card>
      <Row :gutter="16">
        <i-col span="11">
          <Button type="primary" @click="addModelShow">新建角色</Button>
        </i-col>
      </Row>
      <br />
      <Row :gutter="16">
        <i-col span="12">
          <span style="font-size:16px">角色列表</span>
        </i-col>
      </Row>
      <Divider></Divider>
      <Modal v-model="addModel" :mask-closable="false" width="529">
        <span slot="header" style="color:#fff;font-size:16px">创建新角色</span>
        <span class="addFormSpan">
          <Form
            ref="addForm"
            :model="addForm"
            :rules="rules"
            :label-width="80"
            style="width:80%;margin:0 auto"
          >
            <FormItem label="角色名" prop="name">
              <i-input type="text" v-model="addForm.name"></i-input>
            </FormItem>
            <FormItem label="描述" prop="description">
              <i-input type="textarea" v-model="addForm.description"></i-input>
            </FormItem>
          </Form>
        </span>
        <div slot="footer">
          <Button type="primary" @click="roleAdd('addForm')" :loading="addSubmit">保存</Button>
          <Button type="primary" @click="cancel">取消</Button>
        </div>
      </Modal>
      <Table :columns="columns1" :data="data1" border>
        <template slot-scope="{ row }" slot="indexNo">{{row._index+1}}</template>
        <template slot-scope="{ row }" slot="operate">
          <Button type="primary" @click="authorization(row)">菜单授权</Button>
          <Button
            type="primary"
            @click="associateShow(row)"
            style="margin-left:50px;margin-right:50px"
          >关联角色</Button>
          <Button
            type="primary"
            @click="deleteBtn(row.id)"
            :disabled="row.name=='外勤'||row.name=='外勤主管'||row.name=='外勤部经理'||row.name=='支公司内勤'||row.name=='分公司内勤'||row.name=='总公司内勤'?true:false"
          >删除</Button>

          <Button @click="info" v-if="false"></Button>
        </template>
      </Table>
      <Modal v-model="authorizationModel" :mask-closable="false" width="611">
        <span slot="header" style="color:#fff;font-size:16px">菜单权限管理</span>
        <span style="display:inline-block;margin-left:20px">
          <Tree :data="authorizationData" show-checkbox @on-check-change="authorizationCheck"></Tree>
        </span>
        <div slot="footer">
          <Button type="primary" @click="authorizationSubmit" :loading="setSubmit">保存</Button>
          <Button type="primary" @click="authorizationCancel">取消</Button>
        </div>
      </Modal>
      <Modal v-model="associateModel" :mask-closable="false" width="581">
        <span slot="header" style="color:#fff;font-size:16px">成员管理</span>
        <span style="display:inline-block;margin-left:60px">
          <Transfer
            :data="transferData"
            :target-keys="targetKeys"
            :render-format="renderFormat"
            :titles="transferTitle"
            @on-change="onChange"
            filterable
            filter-placeholder="成员姓名"
            :filter-method="filterMethod"
          ></Transfer>
        </span>
        <div slot="footer">
          <Button type="primary" @click="transferSubmit" :loading="roleSubmit">保存</Button>
          <Button type="primary" @click="transferCancel">取消</Button>
        </div>
      </Modal>
      <!-- 删除 -->
      <Modal v-model="delModal" header-hide="true" :mask-closable="false" footer-hide="true" width="450">
        <div>
          <span style="font-size:28px; color:#FF9900;margin: 0 10px;">
            <Icon type="ios-help-circle" />
          </span>
          <span slot="header" style="font-size:16px">删除确认</span>
        </div>
        <span style="display:block;margin:20px 0 20px 60px; font-size:14px;">您确定要删除吗？</span>
        <div style="width:400px; text-align:right;">
          <Button
            type="primary"
            @click="delSubmit"
            :loading="roleSubmit"
            style="margin-right:20px;"
          >确定</Button>
          <Button @click="delCancel">取消</Button>
        </div>
      </Modal>
      <Row>
        <i-col span="24" style="text-align:right;margin-top:20px">
          <Page
            :total="total"
            show-sizer
            show-total
            @on-change="indexChange"
            @on-page-size-change="pageSizeChange"
            :page-size-opts="pageSizeOptions"
          />
        </i-col>
      </Row>
    </Card>
  </div>
</template>
<script>
import Vue from "vue";
export default {
  data() {
    return {
      // 当前页码
      index: 1,
      // 每页记录数量
      pageSize: 10,
      //  每页条数切换的配置
      pageSizeOptions: [5, 10, 15, 20],
      //  总数量
      total: 0,
      form: {
        id: ""
      },
      addModel: false,
      addForm: {
        description: "",
        name: ""
      },
      rules: {
        name: [{ required: true, message: "角色名不能为空", trigger: "blur" }]
      },
      columns1: [
        {
          title: "序号",
          key: "indexNo",
          slot: "indexNo",
          align: "center",
          width: "124"
        },
        {
          title: "角色名称",
          key: "name",
          align: "center",
          width: "300"
        },
        {
          title: "相关描述",
          key: "description",
          align: "center",
          width: "300"
        },
        {
          title: "操作",
          key: "operate",
          slot: "operate",
          align: "center",
          width: "500"
        }
      ],
      data1: [],
      authorizationModel: false,
      // 菜单列表
      authorizationData: null,
      // 勾选列表
      authorizationList: null,
      //当前用户
      currentRoleId: "",
      // 已被赋权限的菜单
      checkList: null,
      associateModel: false,
      transferData: [
        { key: "1", label: "Content 1", id: "111" },
        { key: "2", label: "Content 2", id: "222" },
        { key: "3", label: "Content 3", id: "333" }
      ],
      targetKeys: ["1", "2"],
      transferTitle: ["未添加成员", "已有成员"],
      currentRow: null,
      leftList: null,
      rightList: null,
      newLeftList: null,
      addSubmit: false,
      setSubmit: false,
      roleSubmit: false,
      delModal: false,
      delId: null
    };
  },
  methods: {
    // 新建角色对话框
    addModelShow() {
      this.addModel = true;
      this.$refs["addForm"].resetFields();
    },

    // 新建角色保存
    roleAdd(name) {
      this.$refs[name].validate(valid => {
        //console.log(valid);
        if (valid) {
          this.addSubmit = true;
          let obj = {
            description: this.addForm.description,
            name: this.addForm.name
          };
          this.api.addPrivilegeinput(obj).then(res => {
            // console.log(res);
            if (res.code == 200) {
              this.addModel = false;
              this.addSubmit = false;
              this.rolePages();
              this.info(res.msg);
            } else {
              this.addModel = false;
              this.addSubmit = false;
              this.info(res.msg);
            }
          });
        } else {
        }
      });
    },
    info(tip) {
      this.$Message.warning(tip);
    },
    
    // 关闭modal框
    cancel() {
      this.addModel = false;
      this.$refs["addForm"].resetFields();
    },
    // 菜单授权
    authorization(row) {
      this.currentRoleId = row.id;
      this.roleMenuIds(parseInt(row.id));
      this.authorizationModel = true;
    },
    // 页码切换
    indexChange(e) {
      this.index = e;
      this.rolePages();
    },

    // 每页数量切换
    pageSizeChange(e) {
      this.pageSize = e;
      this.rolePages();
    },

    // 查询角色分页列表
    rolePages() {
      let obj = {
        index: this.index, // 查询页码
        pageSize: this.pageSize // 每页显示数据数量
      };
      this.api.rolePages(obj).then(res => {
        if (res.code === 200) {
          this.data1 = res.data.records;
          this.total = res.data.total;
        }else{
          this.data1 = [];
          this.info(res.msg);
        }
      });
    },
    // 查询树结构
    treeQuery() {
      this.api.treeQuery().then(res => {
        //console.log(res)
        if (res.code == 200) {
          let firstMenu = [];
          let firstMenuIndex = 0;
          if (res.data[0].children != null) {
            res.data[0].children.forEach(element => {
              firstMenu.push({
                pid: element.pid,
                id: element.id,
                title: element.name,
                expand: false,
                checked: false,
                children: []
              });
              if (element.children && element.children != null) {
                element.children.forEach(element => {
                  firstMenu[firstMenuIndex].children.push({
                    pid: element.pid,
                    id: element.id,
                    title: element.name,
                    checked: false
                  });
                });
              }
              firstMenuIndex++;
            });
          }
          this.authorizationData = firstMenu;
        }
      });
    },

    //  删除按钮
    deleteBtn(id) {
      this.delModal = true;
      this.delId = id;
    },
    delSubmit() {
      this.api.roleDelete({ id: this.delId }).then(res => {
        //console.log(res);
        if (res.code === 200) {
          this.$Message.info(res.msg);
          this.delModal = false;
          this.rolePages();
        } else {
          this.delMedal = false;
          this.$Message.info(res.msg);
        }
      });
    },
    delCancel() {
      this.delModal = false;
      this.delId = null;
    },

    // 根据角色id查询关联的菜单权限id
    roleMenuIds(id) {
      this.api.roleMenuIds({ roleId: id }).then(res => {
        //console.log(res)
        this.checkList = res.data; //角色已被授权的菜单列表
        //console.log(this.checkList)
        //this.checkList=this.checkList[(Math.floor(Math.random))]
        //console.log(this.authorizationData);
        if (this.authorizationData != null) {
          this.authorizationData.forEach(element => {
            if (this.checkList.includes(element.id)) {
              element.checked = true;
            } else {
              // 取消时利于重置
              element.checked = false;
            }
            if (element.children && element.children != null) {
              element.children.map(item2 => {
                if (this.checkList.includes(item2.id)) {
                  item2.checked = true;
                } else {
                  item2.checked = false;
                }
                // if (item2.children && item2.children.length > 0) {
                //   item2.children.map(item3 => {
                //     if (this.checkList.includes(item3.id)) {
                //       item3.checked = true;
                //     }
                //   });
                // }
              });
            }
          });
        }
      });
    },

    // 勾选授权菜单树
    authorizationCheck(selectMenu) {
      // console.log(selectMenu);
      if (selectMenu != null) {
        let list = [];
        selectMenu.forEach(element => {
          if (element.children && element.children != null) {
            element.children.forEach(element => {
              list.push(element.id);
            });
          } else {
            list.push(element.id);
          }
        });
        this.authorizationList = Array.from(new Set(list));
        console.log(this.authorizationList);
      } else {
        this.authorizationList = [];
      }
    },

    // 菜单授权保存
    authorizationSubmit() {
      this.setSubmit = true;
      let menuIds = [];
      this.authorizationList.forEach(element => {
        menuIds.push(parseInt(element));
      });
      let obj = {
        menuIds: menuIds.join(","),
        roleId: parseInt(this.currentRoleId)
      };
      this.api.associateMenus(obj).then(res => {
        //console.log(res)
        if (res.code == 200) {
          this.setSubmit = false;
          this.info(res.msg);
          this.authorizationModel = false;
        } else {
          this.setSubmit = false;
          this.info(res.msg);
        }
      });
    },
    // 菜单授权取消
    authorizationCancel() {
      this.setSubmit = false;
      this.authorizationModel = false;
      //重新设置已授权菜单
      // this.authorizationList = this.roleMenuIds(1);
    },
    // 关联角色对话框
    associateShow(row) {
      //console.log(row);
      this.currentRow = row;
      this.associateModel = true;
      this.transferData = [];
      this.targetKeys = [];
      // 获取未拥有角色的职员
      this.api.getNoRoleEmp().then(res => {
        //console.log(res)
        if (res.code == 200) {
          if (res.data.employeeInfo != "") {
            let leftList = [];
            res.data.employeeInfo.forEach(element => {
              if (element.employeeName) {
                this.transferData.push({
                  key: element.employeeId,
                  label: element.employeeName
                });
                leftList.push(element.employeeId);
              }
            });
            this.leftList = leftList;
          }
        }
      });
      // 获取已经是**的职员
      this.api.getHaveThisRoleEmp({ roleId: row.id }).then(res => {
        if (res.code == 200) {
          if (res.data.employeeInfo != "") {
            let rightList = [];
            res.data.employeeInfo.forEach(element => {
              this.transferData.push({
                key: element.employeeId,
                label: element.employeeName
              });
              rightList.push(element.employeeId);
              this.targetKeys.push(element.employeeId);
            });

            this.rightList = rightList;
          }
        }
      });
    },
    filterMethod (data, query) {
      console.log(data,query);
      return data.label.indexOf(query) > -1;
    },
    // 穿梭框复选框后的信息
    renderFormat(item) {
      return item.label;
    },
    onChange(newTargetKeys) {
      //console.log(newTargetKeys,this.existIdList);
      this.targetKeys = newTargetKeys;
      let transferList = [];
      this.transferData.map(item => {
        transferList.push(item.key);
      });
      this.transferList = transferList;
    },
    arrMinus(arr1, arr2) {
      if (arr1.length > arr2.length) {
        let m = {};
        arr1.forEach(function(al) {
          m[al] = al;
        });
        arr2.forEach(function(bl) {
          delete m[bl];
        });
        return Object.keys(m);
      } else {
        let m = {};
        arr2.forEach(function(al) {
          m[al] = al;
        });
        arr1.forEach(function(bl) {
          delete m[bl];
        });
        return Object.keys(m);
      }
    },
    // 取消清除移动，关闭对话框
    transferCancel() {
      this.associateShow(1);
      this.associateModel = false;
      this.roleSubmit = false;
    },
    // 穿梭框提交
    transferSubmit() {
      this.roleSubmit = true;
      this.newLeftList = [];
      this.newLeftList = this.arrMinus(this.transferList, this.targetKeys);

      let obj = {
        grantRoleUsers: this.targetKeys,
        removeRoleUsers: this.newLeftList,
        roleId: this.currentRow.id,
        roleName: this.currentRow.name
      };
      // console.log(obj);

      this.api.reviseRole(obj).then(res => {
        //console.log(res)
        if (res.code == 200) {
          this.targetKeys = [];
          this.roleSubmit = false;
          this.associateModel = false;
          this.info(res.data);
        } else {
          this.roleSubmit = false;
        }
      });
    }
  },
  created() {},
  mounted() {
    this.rolePages();
    this.treeQuery();
  }
};
</script>
<style>
.ivu-transfer-list-body-search-wrapper{
  padding: 8px 5px 0;
  position: absolute;
  top:5px;
  left: 0;
  right: 0;
}
.addFormSpan textarea {
  resize: none;
}
.addFormSpan textarea.ivu-input {
  height: 128px;
}
.ivu-modal-header {
  background-color: #2d8cf0;
}
.ivu-modal-close .ivu-icon-ios-close {
  color: #fff;
}
</style>